<template>
  <!-- 收到的报价单 -->
  <div class="PriceSheet">
    <div class="body">
      <div class="g-con">
        <div class="main">
          <div class="title">{{ t('priceSheet.t2') }}</div>

          <el-tabs
            v-model="activeName"
            type="card"
            class="mt-2"
            @tab-change="tabChange"
          >
            <el-tab-pane
              :label="item.label"
              :name="item.name"
              :key="item.name"
              v-for="item in tabsData"
            >
            </el-tab-pane>
          </el-tabs>

          <!-- 坞修单报价 -->
          <template v-if="activeName === 'dockRepair'">
            <div class="search flexsc">
              <div class="item" style="margin-right: 10px;width: 100px;">
                <el-date-picker
                    style="width: 100%"
                    v-model="searchData.orderYear"
                    type="year"
                    value-format="x"
                    :placeholder="t('year')"
                />
<!--                <el-input
                  v-model="searchData.relationOrderNo"
                  :placeholder="t('invitationQuotation.p1')"
                />-->
              </div>
              <div class="item" style="margin-right: 10px;width: 220px;">
                <el-select-v2
                  style="width: 100%"
                  v-model="searchData.shipId"
                  :options="shipOptions"
                  :placeholder="t('invitationQuotation.p2')"
                  filterable
                  clearable
                />
              </div>
              <el-button
                style="margin-left: 185px;"
                type="primary"
                @click="handleSearch"
              >
                {{ t('invitationQuotation.b1') }}
              </el-button>
              <el-button
                type="primary"
                color="#252628"
                @click="handleReset"
              >
                {{ t('invitationQuotation.b2') }}
              </el-button>
              <el-button
                type="primary"
                color="#252628"
                :disabled="!checkedList.length"
                @click="handleCompare('/user/dockOrderPriceComparative')"
              >
                {{ t('priceSheet.b7') }}
              </el-button>
            </div>
            <div class="g-order-list">
              <div
                class="li mt-2"
                v-for="item in listData"
                :key="item.id"
              >
                <div class="attr">
                  <div class="item">
                    <span>{{ t('invitationQuotation.attr1') }}:</span>
                    <span>{{ item.orderNo }}</span>
                  </div>
                  <div class="item">
                    <span>{{ t('invitationQuotation.attr2') }}:</span>
                    <span>{{ item.dockOrderName }}</span>
                  </div>
<!--                  <div class="item">
                    <span>{{ t('DockOrderOnlineQuotation.t2') }}:</span>
                    <span>{{ item.quotationNo }}</span>
                  </div>-->



                  <div class="item">
                    <span>{{ t('priceSheet.attr1') }}:</span>
                    <span>{{ item.enterpriseName }}</span>
                  </div>

                  <div class="item">
                    <span>{{ t('priceSheet.attr8') }}:</span>
                    <span>{{ item.quotaCreateByName }}</span>
                  </div>

                  <div class="item">
                    <span>{{ t('priceSheet.attr2') }}:</span>
                    <span>{{ isView(item) ? amountFormat(item.amountAfterOffer) || 0 : '***' }}   {{item.quoteOrderCurrency}}</span>
                  </div>
                  <div class="item">
                    <span>{{ t('priceSheet.attr3') }}:</span>
                    <span>{{ dateFormat(item.submitTime) }}</span>
                  </div>
                  <div class="item">
                    <span>{{ t('priceSheet.attr9') }}:</span>
                    <span>{{ item.totalRepairPeriod }}  {{t('priceSheet.attr10')}}</span>
                  </div>


                  <div class="item">
                    <span>{{ t('priceSheet.attr6') }}:</span>
                    <span>{{ dateFormat(item.quotationEndTime) }}</span>
                  </div>
                  <div class="item">
                    <span>{{ t('priceSheet.attr7') }}:</span>
                    <span>{{ item.statusDisplay }}</span>
                  </div>
                </div>

                <div class="bottom mt-3">
                  <div class="">
                    <el-button
                      type="primary"
                      @click="open(item, '/user/dockOrder/onlineQuotation')"
                    >
                      {{ t('priceSheet.b1') }}
                    </el-button>
                    <el-button
                      v-if="isCreator(item)"
                      type="primary"
                      @click="handelSendMsg(item)"
                    >
                      {{ t('DockOrderOnlineQuotation.t7') }}
                    </el-button>
                    <!-- status	0已拒绝，1中标未确认，2中标已确认，3未提交，4未中标 -->
                    <el-button
                      v-if="item.status === '4' && item.canConfirmQuota && isCreator(item) && item.id === item.lastId"
                      type="primary"
                      @click="handleConfirmBid(item)"
                    >
                      {{ t('DockOrderOnlineQuotation.t8') }}
                    </el-button>
                  </div>
                  <div class="">
                    <el-button
                      v-if="isCreator(item)"
                      type="primary"
                      color="#252628"
                      @click="handleAuth(item)"
                    >
                      {{ t('userCenter.b11') }}
                    </el-button>
                  </div>
                </div>

                <div
                  v-if="isCreator(item)"
                  class="checked"
                >
                  <el-checkbox
                    v-model="item.checked"
                    :label="t('priceSheet.l4')"
                    :disabled="checkedDisabled(item) || item.quotationEndTime > now"
                    @change="checkedChange($event, item)"
                  />
                </div>
              </div>
            </div>
          </template>

          <!-- 采购单报价 -->
          <template v-if="activeName === 'procurement'">
            <div class="search flexsc">
              <div class="item">
                <el-input
                  v-model="searchData.relationOrderNo"
                  :placeholder="t('invitationQuotation.attr1_2')"
                />
              </div>
              <div class="item">
                <el-select-v2
                  v-model="searchData.shipId"
                  :options="shipOptions"
                  :placeholder="t('invitationQuotation.p2')"
                  clearable
                  filterable
                />
              </div>
              <el-button
                type="primary"
                @click="handleSearch"
              >
                {{ t('invitationQuotation.b1') }}
              </el-button>
              <el-button
                type="primary"
                color="#252628"
                @click="handleReset"
              >
                {{ t('invitationQuotation.b2') }}
              </el-button>
              <el-button
                type="primary"
                color="#252628"
                :disabled="!checkedList.length"
                @click="handleCompare('/user/procurementPriceComparative')"
              >
                {{ t('priceSheet.b7') }}
              </el-button>
            </div>
            <div class="g-order-list">
              <div
                class="li mt-2"
                v-for="item in listData"
                :key="item.id"
              >
                <div class="attr">
                  <div class="item">
                    <span>{{ t('invitationQuotation.attr1_2') }}:</span>
                    <span>{{ item.orderNo }}</span>
                  </div>
                  <div class="item">
                    <span>{{ t('invitationQuotation.attr2_2') }}:</span>
                    <span>{{ item.procureOrderName }}</span>
                  </div>
                  <div class="item">
                    <span>{{ t('userCenter.darrt2') }}:</span>
                    <span>{{ item.shippingName }}</span>
                  </div>
<!--                  <div class="item">
                    <span>{{ t('DockOrderOnlineQuotation.t2') }}:</span>
                    <span>{{ item.quotationNo }}</span>
                  </div>-->
                  <div class="item">
                    <span>{{ t('priceSheet.attr1') }}:</span>
                    <span>{{ item.enterpriseName }}</span>
                  </div>
                  <div class="item">
                    <span>{{ t('priceSheet.attr8') }}:</span>
                    <span>{{ item.quotaCreateByName }}</span>
                  </div>

                  <div class="item">
                    <span>{{ t('priceSheet.attr2') }}:</span>
                    <span>{{ isView(item) ? amountFormat(item.quotaAmountTotal) || 0 : '***' }}&nbsp;&nbsp;{{item.quoteOrderCurrency}}</span>
                  </div>
                  <div class="item">
                    <span>{{ t('priceSheet.attr3') }}:</span>
                    <span>{{ dateFormat(item.submitTime) }}</span>
                  </div>
                  <div class="item">
                    <span>{{ t('priceSheet.attr9') }}:</span>
                    <span>{{ item.totalRepairPeriod }}</span>
                  </div>
                  <div class="item">
                    <span>{{ t('priceSheet.attr6') }}:</span>
                    <span>{{ dateFormat(item.quotationEndTime) }}</span>
                  </div>
                  <div class="item">
                    <span>{{ t('priceSheet.attr7') }}:</span>
                    <span>{{ item.statusDisplay }}</span>
                  </div>
                </div>

                <div class="bottom mt-3">
                  <div class="">
                    <el-button
                      type="primary"
                      @click="open(item, '/user/procurement/onlineQuotation')"
                    >
                      {{ t('priceSheet.b1') }}
                    </el-button>
                    <el-button
                      v-if="isCreator(item)"
                      type="primary"
                      @click="handelSendMsg(item)"
                    >
                      {{ t('DockOrderOnlineQuotation.t7') }}
                    </el-button>
                    <!-- status	0已拒绝，1中标未确认，2中标已确认，3未提交，4未中标 -->
                    <el-button
                      v-if="item.status === '4' && item.canConfirmQuota && isCreator(item) && item.id === item.lastId"
                      type="primary"
                      @click="handleConfirmBid(item)"
                    >
                      {{ t('DockOrderOnlineQuotation.t8') }}
                    </el-button>
                  </div>
                  <div class="">
                    <el-button
                      v-if="isCreator(item)"
                      type="primary"
                      color="#252628"
                      @click="handleAuth(item)"
                    >
                      {{ t('userCenter.b11') }}
                    </el-button>
                  </div>
                </div>

                <div
                  v-if="isCreator(item)"
                  class="checked"
                >
                  <el-checkbox
                    v-model="item.checked"
                    :label="t('priceSheet.l4')"
                    :disabled="checkedDisabled(item) || item.quotationEndTime > now"
                    @change="checkedChange($event, item)"
                  />
                </div>
              </div>
            </div>
          </template>

          <!-- 外协单报价 -->
          <template v-if="activeName === 'externalAssistance'">
            <div class="search flexsc">
              <div class="item">
                <el-input
                  v-model="searchData.relationOrderNo"
                  :placeholder="t('invitationQuotation.attr1_3')"
                />
              </div>
              <div class="item">
                <el-select-v2
                  v-model="searchData.shipId"
                  :options="shipOptions"
                  :placeholder="t('invitationQuotation.p2')"
                  clearable
                  filterable
                />
              </div>
              <el-button
                type="primary"
                @click="handleSearch"
              >
                {{ t('invitationQuotation.b1') }}
              </el-button>
              <el-button
                type="primary"
                color="#252628"
                @click="handleReset"
              >
                {{ t('invitationQuotation.b2') }}
              </el-button>
              <el-button
                type="primary"
                color="#252628"
                :disabled="!checkedList.length"
                @click="handleCompare('/user/externalAssistancePriceComparative')"
              >
                {{ t('priceSheet.b7') }}
              </el-button>
            </div>
            <div class="g-order-list">
              <div
                class="li mt-2"
                v-for="item in listData"
                :key="item.id"
              >
                <div class="attr">
                  <div class="item">
                    <span>{{ t('invitationQuotation.attr1_3') }}:</span>
                    <span>{{ item.orderNo }}</span>
                  </div>
                  <div class="item">
                    <span>{{ t('invitationQuotation.attr2_3') }}:</span>
                    <span>{{ item.assistOrderName }}</span>
                  </div>
                  <div class="item">
                    <span>{{ t('userCenter.darrt2') }}:</span>
                    <span>{{ item.shippingName }}</span>
                  </div>
<!--                  <div class="item">
                    <span>{{ t('DockOrderOnlineQuotation.t2') }}:</span>
                    <span>{{ item.quotationNo }}</span>
                  </div>-->
                  <div class="item">
                    <span>{{ t('priceSheet.attr1') }}:</span>
                    <span>{{ item.enterpriseName }}</span>
                  </div>
                  <div class="item">
                    <span>{{ t('priceSheet.attr8') }}:</span>
                    <span>{{ item.quotaCreateByName }}</span>
                  </div>

                  <div class="item">
                    <span>{{ t('priceSheet.attr2') }}:</span>
                    <span>{{ isView(item) ? amountFormat(item.quotaAmountTotal) || 0 : '***' }}&nbsp;&nbsp;{{item.quoteOrderCurrency}}</span>
                  </div>
                  <div class="item">
                    <span>{{ t('priceSheet.attr3') }}:</span>
                    <span>{{ dateFormat(item.submitTime) }}</span>
                  </div>
                  <div class="item">
                    <span>{{ t('priceSheet.attr9') }}:</span>
                    <span>{{ item.totalRepairPeriod }}</span>
                  </div>
                  <div class="item">
                    <span>{{ t('priceSheet.attr6') }}:</span>
                    <span>{{ dateFormat(item.quotationEndTime) }}</span>
                  </div>
                  <div class="item">
                    <span>{{ t('priceSheet.attr7') }}:</span>
                    <span>{{ item.statusDisplay }}</span>
                  </div>
                </div>

                <div class="bottom mt-3">
                  <div class="">
                    <el-button
                      type="primary"
                      @click="open(item, '/user/externalAssistance/onlineQuotation')"
                    >
                      {{ t('priceSheet.b1') }}
                    </el-button>
                    <el-button
                      v-if="isCreator(item)"
                      type="primary"
                      @click="handelSendMsg(item)"
                    >
                      {{ t('DockOrderOnlineQuotation.t7') }}
                    </el-button>
                    <!-- status	0已拒绝，1中标未确认，2中标已确认，3未提交，4未中标 -->
                    <el-button
                      v-if="item.status === '4' && item.canConfirmQuota && isCreator(item) && item.id === item.lastId"
                      type="primary"
                      @click="handleConfirmBid(item)"
                    >
                      {{ t('DockOrderOnlineQuotation.t8') }}
                    </el-button>
                  </div>
                  <div class="">
                    <el-button
                      v-if="isCreator(item)"
                      type="primary"
                      color="#252628"
                      @click="handleAuth(item)"
                    >
                      {{ t('userCenter.b11') }}
                    </el-button>
                  </div>
                </div>

                <div
                  v-if="isCreator(item)"
                  class="checked"
                >
                  <el-checkbox
                    v-model="item.checked"
                    :label="t('priceSheet.l4')"
                    :disabled="checkedDisabled(item) || item.quotationEndTime > now"
                    @change="checkedChange($event, item)"
                  />
                </div>
              </div>
            </div>
          </template>

          <div class="flexcc mt-3">
            <el-pagination
              layout="prev, pager, next"
              :hide-on-single-page="total <= page.pageSize"
              :total="total"
              v-model:current-page="page.pageNum"
              :page-size="page.pageSize"
              @current-change="handleCurrentChange"
            >
            </el-pagination>
          </div>
        </div>
      </div>
    </div>

    <!-- 确认中标 -->
    <ConfirmBid
      v-if="dialogConfirmBid"
      :visible="dialogConfirmBid"
      :objId="editId"
      :type="activeName"
      @close="dialogConfirmBid = false"
      @getList="getList"
    />

    <!-- 授权查看人 -->
    <AuthView
      v-if="authViewDialog"
      v-model="authViewDialog"
      :obj-id="objId"
      :obj-table="objTable"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onBeforeMount, watch, nextTick, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { dockQuotationQueryReceiveQuotaApi } from '@/service/dockOrder.js'
import { procureQuotationQueryReceiveQuotaApi } from '@/service/procurement.js'
import { assistQuotationQueryReceiveQuotaApi } from '@/service/externalAssistance.js'
import { shippingListByEnterpriseIdApi } from '@/service/shipping'
import { useI18n } from 'vue-i18n'
import { dateFormat, amountFormat } from '@/utils/index'
import moment from 'moment'
import useDialogue from '@/stores/dialogue'
import useLogin from '@/stores/login'
import ConfirmBid from './ConfirmBid.vue'
import AuthView from '@/components/AuthView.vue'

import useDict from '@/hooks/useDict'
const { dictData, getDictData } = useDict()
const now =  Date.now() / 1000
const router = useRouter()
const route = useRoute()

const type = route.query.type
const relationOrderNo = route.query.relationOrderNo

const { t, locale } = useI18n()
watch(locale, () => {
  init()
})

onBeforeMount(() => {
  init()
})

const storeDialogue = useDialogue()
const { setDialogVisible, setActivePerson } = storeDialogue
const storeLogin = useLogin()

// tab
const tabsData = ref([])
const setTabsData = () => {
  const arr = [
    {
      label: t('priceSheet.l1'),
      name: 'dockRepair',
      role: ['05', '06'] // 船东/船管
    },
    {
      label: t('priceSheet.l2'),
      name: 'procurement',
      role: ['05', '06', '07'] // 船东/船管/修船厂
    },
    {
      label: t('priceSheet.l3'),
      name: 'externalAssistance',
      role: ['05', '06', '07'] // 船东/船管/修船厂
    }
  ]

  tabsData.value = arr.filter((item) => item.role.includes(storeLogin.userInfo.customerClassCode))
  activeName.value = type || tabsData.value[0].name
}
const activeName = ref('dockRepair')
const tabChange = (value) => {
  page.value.pageNum = 1
  searchData.value = {}
  listData.value = []
  checkedList.value = []
  getList()
}

// 查询
const searchData = ref({
  relationOrderNo
})
const shipOptions = ref([])
const getShippingList = () => {
  shippingListByEnterpriseIdApi().then(({ rows }) => {
    shipOptions.value = rows.map((r) => {
      return {
        value: r.id,
        label: r.shippingName
      }
    })
  })
}
const handleSearch = () => {
  page.value.pageNum = 1
  if (searchData.value.shipId) {
    searchData.value.shipList = [searchData.value.shipId]
  }
  getList()
}
const handleReset = () => {
  page.value.pageNum = 1
  searchData.value = {}
  getList()
}

// 勾选的比价单
const checkedList = ref([])
const checkedChange = (val, item) => {
  if (val) {
    checkedList.value.push(item)
  } else {
    checkedList.value = checkedList.value.filter((c) => c.id !== item.id)
  }
}

// 只能勾选同一个 orderNo
const checkedDisabled = (item) => {
  return Boolean(checkedList.value.length && !checkedList.value.some((c) => c.orderNo === item.orderNo))
}

// 加入比价
const handleCompare = (path) => {
  const url = router.resolve({
    path,
    query: {
      // activeName: activeName.value,
      checkedList: checkedList.value.map((item) => item.id).join(',')
    }
  })
  window.open(url.href)
}

// 列表
const listData = ref([])
const page = ref({
  pageNum: 1, // 当前页码
  pageSize: 6 // 每页条数
})
const total = ref(0) // 总数
const getList = () => {
  const apiObj = {
    dockRepair: dockQuotationQueryReceiveQuotaApi,
    procurement: procureQuotationQueryReceiveQuotaApi,
    externalAssistance: assistQuotationQueryReceiveQuotaApi
  }
  const activeApi = apiObj[activeName.value]

  activeApi(page.value, searchData.value).then(({ data: rows, total: t }) => {
    // 0已拒绝，1中标未确认，2中标已确认，3未提交，4未中标
    rows.forEach((item) => {
      item.statusDisplay = dictData.value['quotation_status'].find((d) => d.dictValue === item.status)?.dictLabel
      item.checked = checkedList.value.some((c) => c.id === item.id)
    })
    console.log('rows', rows)
    listData.value = rows
    total.value = t
  })
}
// 分页
const handleCurrentChange = (val) => {
  getList()
}

// 查看
const open = (item, path) => {
  const url = router.resolve({
    path,
    query: {
      id: item.id
    }
  })
  window.open(url.href)
}

// 未到期不可查看
const isView = (item) => {
  return Number(moment().format('X')) > Number(item.quotationEndTime)
}

// 发消息
const handelSendMsg = (item) => {
  setDialogVisible(true)
  setActivePerson({
    customerName: item.quotaCreateByName,
    customerId: item.quotaCreateBy
  })
}

// 正在操作的id
const editId = ref(null)

// 确认中标
const dialogConfirmBid = ref(false)
const handleConfirmBid = (item) => {
  dialogConfirmBid.value = true
  editId.value = item.id
}

// 授权查看人
const objTable = computed(() => {
  const obj = {
    dockRepair: 'shcw_quotation_dock_order',
    procurement: 'shcw_quotation_procure_order',
    externalAssistance: 'shcw_quotation_assist_order'
  }
  return obj[activeName.value]
})
const objId = ref(null)
const authViewDialog = ref(false)
const handleAuth = ({ id }) => {
  authViewDialog.value = true
  objId.value = id
}
const isCreator = ({ orderCreateBy }) => {
  return orderCreateBy === storeLogin.userInfo.id
}

//
const init = async () => {
  setTabsData()
  getShippingList()
  await getDictData('quotation_status')
  handleSearch()
}
</script>

<style scoped lang="scss">
.PriceSheet {
  .el-button {
    min-width: 140px;
  }
  .body {
    padding: 30px 0 70px;
    background: #f5f5f5;
    margin-bottom: -76px;

    .main {
      background: #fff;
      padding: 25px 35px;
      .title {
        border-bottom: 2px solid #212121;
        padding-bottom: 20px;
        text-transform: uppercase;
        font-weight: bold;
        font-size: 20px;
        color: var(--mainColor);
      }
      .search {
        margin-top: 25px;
        .item {
          width: 200px;
          margin-right: 20px;
        }
      }

      .bottom {
        display: grid;
        grid-template-columns: 495px auto;
      }
    }
  }
}
</style>
